package com.shelpe.services.simbasync.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.shelpe.services.simbasync.dto.OrderCustomerDto;
import com.shelpe.services.simbasync.model.OrderCustomer;
import com.shelpe.services.simbasync.model.PurchaseOrder;
import com.shelpe.services.simbasync.service.OrderCustomerService;
import com.shelpe.services.simbasync.service.simbaproxy.OrderProxy;
import com.shelpe.services.simbasync.service.simbaproxy.OrderProxy.OrderResponse;
import com.shelpe.services.simbasync.util.Util;

@RestController
@RequestMapping(value="/simbasync")
public class OrderCustomerController {
	
	private static final Logger logger = LoggerFactory.getLogger(OrderCustomerController.class);
	
	@Autowired
	private OrderCustomerService service;
	
	@Autowired
	private OrderProxy orderProxy;
	
	@Value("${simbasync.appKeyUserId}")
	private Long appKeyUserId;
	
	@RequestMapping("/@deleteordercustomer")
	@ResponseBody
	public OrderCustomerDto deleteAllOrderCustomer(){
		
		logger.info("deleteAllOrderCustomer begin");
		Date beginProcessTime = new Date();
		OrderCustomerDto dto = new OrderCustomerDto();
		dto.setProcess("deleteAllOrderCustomer");
		
		dto.setDeleteNum(service.deleteAllOrderCustomer());
		
		Date endProcessTime = new Date();
		long durTime = endProcessTime.getTime() - beginProcessTime.getTime();
		dto.setDurTime(durTime);
		logger.info("deleteAllOrderCustomer end durTime {}, deleteNum {}", durTime, dto.getDeleteNum());
		
		return dto;
	}
	
	@RequestMapping("/@syncordercustomer")
	@ResponseBody
	public OrderCustomerDto syncOrderCustomer(){
		
		logger.info("syncOrderCustomer begin");
		Date beginProcessTime = new Date();
		OrderCustomerDto dto = new OrderCustomerDto();
		dto.setProcess("syncOrderCustomer");
		
		List<OrderCustomer> list = service.getOrderCustomerFromRpt();
		
		dto.setAddNum(service.insertOrderCustomerBatch(list));
		
		Date endProcessTime = new Date();
		long durTime = endProcessTime.getTime() - beginProcessTime.getTime();
		dto.setDurTime(durTime);
		logger.info("syncOrderCustomer end durTime {}, addNum {}", durTime, dto.getAddNum());
		
		return dto;
	}
	
	@RequestMapping("/articlecode/{article_code}/@order")
	@ResponseBody
	public OrderCustomerDto syncOrderByArticleCode(@PathVariable("article_code") String articleCode,
			@RequestParam(value = "start_time", required = false) String startTimeStr, 
			@RequestParam(value = "end_time", required = false) String endTimeStr){
		
		logger.info("syncOrderByArticleCode begin articleCode {}", articleCode);
		OrderCustomerDto dto = new OrderCustomerDto();
		dto.setProcess("syncOrder");
		int pageNo = 1;
		int pageSize = 200;
		Date beginProcessTime = new Date();
		Date startTime = beginProcessTime;
		Date endTime = beginProcessTime;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		if(startTimeStr != null && endTimeStr != null){
			try {
				startTime = sdf.parse(startTimeStr);
				endTime = sdf.parse(endTimeStr);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			Date lastTime =service.getLastTimeFromOrder(articleCode);
			startTime = Util.getStartTime(lastTime);
		}
		String startTimeTemp = sdf.format(startTime);
		String endTimeTemp = sdf.format(endTime);
		logger.info(">>>syncOrderByArticleCode startTime: {}, endTime: {}", startTimeTemp, endTimeTemp);
		OrderResponse res = orderProxy.getOrder(appKeyUserId, articleCode, startTimeTemp, endTimeTemp, pageNo, pageSize);
		List<PurchaseOrder> totalOrder = new ArrayList<PurchaseOrder>();
		
		if(res != null && res.getOrderRes() != null){
			if(res.getOrderRes().getBizOrder() != null){
				List<PurchaseOrder> subList = service.translateOrder(res.getOrderRes().getBizOrder().getOrderDto());
				totalOrder.addAll(subList);
			}
			
			Integer totalItem = res.getOrderRes().getTotalItem();
			logger.info(">>>syncOrderByArticleCode totalItem {}", totalItem);
			if(totalItem != null){
				int pages = totalItem / pageSize;
				if(totalItem % pageSize > 0){
					pages++;
				}
				
				for(int i = 2; i <= pages; i++){ 
					res = orderProxy.getOrder(appKeyUserId, articleCode, startTimeTemp, endTimeTemp, i, pageSize);
					if(res != null && res.getOrderRes() != null 
							&& res.getOrderRes().getBizOrder() != null){
						
						List<PurchaseOrder> subList = service.translateOrder(res.getOrderRes().getBizOrder().getOrderDto());
						totalOrder.addAll(subList);
					}
				}
			}
		}
		
		if(totalOrder.size() > 0 && startTimeStr != null && endTimeStr != null){//先删除	
			service.deleteOrderByTimeRange(articleCode, startTime, endTime);	
		}
		
		dto.setAddNum(service.insertOrderBatch(totalOrder));
		Date endProcessTime = new Date();
		long durTime = endProcessTime.getTime() - beginProcessTime.getTime();
		dto.setDurTime(durTime);
		
		return dto;
	}
	

}
